<template>
    <div class="course-list flex flex-col sm:flex-row dark:bg-regal-dark w-full">
        <div :class="'w-full ml-0 sm:ml-2 mt-2 sm:mt-0' ">
            <Search :search="search" :reset="reset">
                <template v-slot:body>
                    <el-form-item label="日期">
                        <el-date-picker
                            v-model="timeArr"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                    <el-form-item label="用户名">
                        <el-select v-model="query.user_id" placeholder="请选择" style="width: 100px">
                            <el-option v-for="item in customerList" :key="item.id" :label="item.username" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="老师名">
                        <el-select v-model="query.teacher_id" placeholder="请选择" style="width: 100px">
                            <el-option v-for="item in lessonConfig.teacherList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="预约状态">
                        <el-select
                            v-model="query.reservation_status"
                            placeholder="请选择"
                            style="width: 120px"
                        >
                            <el-option
                                v-for="item in lessonConfig.reservationStatus"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </template>
            </Search>
            <div class="table-default">
                <div class="pt-5 pl-2 flex align-middle">
                    <el-button type="primary" @click="handleAdd"><Icon name="plus" className="w-4 h-4 mr-1" /> 添加预约</el-button>
                    <div class="text-wrap ml-3"><span>未开始课时共：{{allData.noStart}}分钟</span><span class="ml-3">进行中课时共：{{allData.ing}}分钟</span><span class="ml-3">已完成课时共：{{allData.end}}分钟</span></div>
                </div>
                <el-table
                    :data="tableData"
                    class="course-table mt-3"
                    border
                    style="width: 100%;height: calc(100% - 100px);"
                >
                    <el-table-column
                        v-for="item in headerConfig"
                        :key="item.prop"
                        :prop="item.prop"
                        :label="item.label"
                    >
                    </el-table-column>
                    <el-table-column label="操作" :width="200">
                        <template #default="{ row }">
                            <el-button type="text" v-if="row.status == 1" @click="cancel(row)">取消预约</el-button>
                            <el-button type="text" v-else-if="row.status == 4" @click="editLessonTime(row)">修改实销课时</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="mt-3" background layout="prev, pager, next" @current-change="changePage" @size-change="changeLimit"  :current-page="Pages.current_page" :page-sizes="Pages.per_page" :total="Pages.total" />
            </div>
            <el-dialog v-model="visible" title="添加课时" destroy-on-close>
                <div class="edit-dialog">
                    <el-form :label-width="140" :model="form" ref="formRef" :rules="rules">
                        <el-form-item label="用户名" prop="user_id">
                            <el-select v-model="form.user_id">
                                <el-option
                                    v-for="item in customerList"
                                    :key="item.id"
                                    :label="item.username"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="老师名" prop="teacher_id" v-if="userStore.getId == 1">
                            <el-select v-model="form.teacher_id"  @change="getSubjectOption">
                                <el-option
                                    v-for="item in lessonConfig.teacherList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="日期" prop="lesson_date">
                            <el-date-picker
                                style="width: 100%"
                                v-model="form.lesson_date"
                                type="dates"
                                format="YYYY/MM/DD"
                                value-format="YYYY-MM-DD"
                                placeholder="选择日期（可多选）"
                            />
                        </el-form-item>
                        <el-form-item label="上课时间" prop="lesson_time">
                            <el-select v-model="form.lesson_time" multiple placeholder="请选择">
                                <el-option v-for="item in lessonTime" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="学科" prop="subject_id">
                            <el-cascader style="width: 100%" :options="subjectOption"  v-model="form.subject_id" clearable />
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="visible = false">取消</el-button>
                        <el-button type="primary" @click="confirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <el-dialog v-model="editLessonTimeVisible" title="修改实销课时" :width="420">
                <div class="edit-dialog">
                    <el-form :label-width="140" :model="form" ref="formRef" :rules="rules">
                        <el-form-item label="课时" prop="user_id">
                            <el-input-number v-model="lessonTimeNum" min="0" :max="record.lessons"></el-input-number>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="editLessonTimeVisible = false">取消</el-button>
                        <el-button type="primary" @click="editConfirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, reactive } from 'vue'
import { Code } from '/admin/enum/app'
import Message from '/admin/support/message'
import Http from '/admin/support/http'
import { useUserStore } from '/admin/stores/modules/user'

const userStore = useUserStore()
const lessonTime = ref([])
const lessonConfig = ref({})
const timeArr = ref([])
const query = ref({
    user_id: '',
    teacher_id: '',
    reservation_status: '',
})
const formRef = ref(null)
const form = ref({
    user_id: '',
    teacher_id: '',
    lesson_date: [],
    lesson_time: [],
    subject_id: [],
})

const rules = ref({
    user_id: [
        { required: true, message: '请选择用户名', trigger: 'change' },
    ],
    teacher_id: [
        { required: true, message: '请选择老师名', trigger: 'change' },
    ],
    lesson_date: [
        { required: true, message: '请选择日期', trigger: 'change' },
    ],
    lesson_time: [
        { required: true, message: '请选择上课时间', trigger: 'change' },
    ],
    subject_id: [
        { required: true, message: '请选择学科', trigger: 'change' },
    ],
})
const editLessonTimeVisible = ref(false)
const lessonTimeNum = ref(0)
const record = ref({})
const editLessonTime = (row: any) => {
    record.value = row
    lessonTimeNum.value = row.lessons
    editLessonTimeVisible.value = true
}
const editConfirm = async () => {
    const { data } = await Http.post('/reservation/editLessonTime', {
        id: record.value.id,
        lessons: lessonTimeNum.value
    })
    if (data.code === Code.SUCCESS) {
        Message.success('修改成功')
        editLessonTimeVisible.value = false
        search()
    } else {
        Message.error(data.message)
    }
}



const subjectOption = ref([])
const getSubjectOption = async () => {
    console.log(123123)
    const { data } = await Http.post('/reservation/getSubjects', {
        teacher_id: form.value.teacher_id,
    })
    if (data.code === Code.SUCCESS) {
        subjectOption.value = data.data
    } else {
        Message.error(data.message)
    }
}

//获取所有客户列表
const customerList = ref([])
const getCustomerList = async () => {
    const { data } = await Http.get('/lessonHour/customerList')
    if (data.code === Code.SUCCESS) {
        customerList.value = data.data
    } else {
        Message.error(data.message)
    }
}

//获取上课时间
const getLessonTime = async () => {
    const { data } = await Http.get('/reservation/getLessonTime')
    if (data.code === Code.SUCCESS) {
        lessonTime.value = data.data
    } else {
        Message.error(data.message)
    }
}

//获取基础配置
const getLessonConfig = async () => {
    const { data } = await Http.get('/lessonHour/lessonConfig')
    if (data.code === Code.SUCCESS) {
        lessonConfig.value = data.data
    } else {
        Message.error(data.message)
    }
}

const confirm = () => {
    nextTick(() => {
        formRef.value.validate(async (valid: boolean) => {
            if (valid) {
                const params = {
                    user_id: form.value.user_id,
                    teacher_id: form.value.teacher_id,
                    lesson_date: form.value.lesson_date.join(','),
                    lesson_time: form.value.lesson_time.join(','),
                    subject_id: form.value.subject_id[1]
                }
                const { data } = await Http.post('/reservation/add', params)
                if (data.code === Code.SUCCESS) {
                    Message.success('添加成功')
                    visible.value = false
                    search()
                } else {
                    Message.error(data.message)
                }
            }
        })
    })
}


const Pages = {
    current_page: 1,
    per_page: 10,
    total: 0
}

const headerConfig = [
    {
        prop: 'lesson_date',
        label: '日期',
    },
    {
        prop: 'customer_name',
        label: '用户名',
    },
    {
        prop: 'teacher_name',
        label: '老师',
    },
    {
        prop: 'subject_name',
        label: '学科',
    },
    {
        prop: 'lesson_time',
        label: '上课时间',
    },
    {
        prop: 'status_text',
        label: '状态',
    },
    {
        prop: 'reserve_name',
        label: '预约人',
    },
    {
        prop: 'reserve_time',
        label: '预约时间',
    },
    {
        prop: 'lessons',
        label: '课时',
    },
    {
        prop: 'cancel_name',
        label: '取消人',
    }
]
const tableData = ref([])
const visible = ref(false)
const allData = reactive({
    noStart: 0,
    ing: 0,
    end: 0
})

const getAllData = async () => {
    const { data } = await Http.get('/reservation/lessonCount')
    if (data.code === Code.SUCCESS) {
      allData.noStart =   data.data.find((item: any) => item.status == 1).lessons || 0
      allData.ing =   data.data.find((item: any) => item.status == 2).lessons || 0
      allData.end =   data.data.find((item: any) => item.status == 4).lessons  || 0

    } else {
        Message.error(data.message)
    }
}

const cancel = (row: any) => {
    Message.confirm('确定取消预约吗？', async () => {
        const { data } = await Http.post('/reservation/cancel', { id: row.id })
        if (data.code === Code.SUCCESS) {
            search()
            Message.success('取消成功')
        } else {
            Message.error(data.message)
        }
    })
}


const changePage = (val: number) => {
    Pages.current_page = val
    search()
}

const changeLimit = (val: number) => {
    Pages.per_page = val
    search()
}

const reset = () => {
    query.value = {
        user_id: '',
        teacher_id: '',
        reservation_status: '',
    }
    timeArr.value = []
    search()
}

const handleAdd = () => {
    form.value = {
        user_id: '',
        teacher_id: '',
        lesson_date: [],
        lesson_time: [],
        subject_id: [],
    }
    getLessonTime()
    visible.value = true
}
const search = async () => {
    const params = {
        user_id: query.value.user_id,
        teacher_id: query.value.teacher_id,
        reservation_status: query.value.reservation_status,
        page: Pages.current_page,
        limit: Pages.per_page,
    }

    if (timeArr.value.length) {
        params.start_time = timeArr.value[0]
        params.end_time = timeArr.value[1]
    }
    const { data } = await Http.get('/reservation/list', params)
    if (data.code === Code.SUCCESS) {
        tableData.value = data.data.map((item: any) => {
            item.status_text = lessonConfig.value.reservationStatus.find((status: any) => status.id == item.status)?.name
            return item
        })
        Pages.total = data.total
    } else {
        Message.error(data.message)
    }

    console.log('search')
}



onMounted(() => {
    getCustomerList()
    getLessonConfig()
    search()
    getAllData()
})

</script>

<style scoped lang="scss">
.course-list {
    height: calc(100vh - 120px);
}
.table-default {
    height: calc(100% - 120px);
}
.course-table {
    background: #fff;
    .table {
        width: 100%;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        .course-header {
            height: 60px;
            td {
                text-align: center;
                border-right: 1px solid #ebeef5;
                border-bottom: 1px solid #e1e4e8;
            }
        }
        .course-tr {
            border-bottom: 1px solid #e1e4e8;

            .time {
                width: 100px;
                text-align: center;
                border-right: 1px solid #ebeef5;
            }
            .course-item {
                border-right: 1px solid #ebeef5;
                width: calc(100% / 7.6);
                height: 110px;
                padding: 4px;
                .active {
                    height: 100%;
                    color: #7C93C3;
                    background: #DFF5FF;
                    border-radius: 4px;
                    padding: 10px;
                }
            }
        }
    }
}
.edit-dialog {
    padding: 36px;
}
</style>
